﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using MyAppAPI.Models;
using MyAppAPI.Models.UserInfoModel;
using MyAppAPI.ParamModel;
using MyAppAPI.Services.interfaceService;

namespace MyAppAPI.Controllers
{
    [Route("api/")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService userService;
        private readonly IUserInfoService userInfoService;
        private readonly IUserMenuService userMenuService;
        private readonly IMemoryCache memoryCache;// 本地缓存
        public UserController(IUserService userService, IUserMenuService userMenuService, IUserInfoService userInfoService, IMemoryCache memoryCache) 
        {
            this.userService = userService;
            this.userInfoService = userInfoService;
            this.userMenuService = userMenuService;
            this.memoryCache = memoryCache;
        }

        [Route("permission/getMenu")]
        [HttpPost]
        public PermissionData GetMenu([FromBody]UserLogin login)
        {
            PermissionData data = null;
            int userId = 0;
            bool existUser = userService.ExisUser(login.username,login.password,ref userId);
            if (!existUser)
            {
                data=new PermissionData();
                data.data = null;
                data.code = 20000;
                return data;
            }
            List<MenuInfo> menuLists = userMenuService.GetMenuInfo(userId);
            data = new PermissionData();
            MenuData menuData=new MenuData ();
            menuData.menu = menuLists;
            data.data = menuData;
            data.code = 20000;
            return data;
        }
        [Route("user/getUser")]
        [HttpGet]
        public UserInfoData GetUser(string? name,int page,int limit)
        {
            UserInfoData userInfoData = null;
            bool flag = memoryCache.TryGetValue<UserInfoData>("userInfoData" + page + limit + "GETUSER" + name, out userInfoData);
            if (!flag)
            {
                // 1.1 查询数据库
                userInfoData = userInfoService.GetAllUser(name, page, limit);

                var cacheEntryOptions = new MemoryCacheEntryOptions()
                // 限制单个缓存数据大小
                .SetSize(1024)
                // 自动失效
                .SetSlidingExpiration(TimeSpan.FromSeconds(50));

                // 1.2 添加到缓存
                memoryCache.Set<UserInfoData>("userInfoData", userInfoData, cacheEntryOptions);
            }
            return userInfoData;
        }
    }
}
